var basePath = $('base').attr('href');

/*ajax请求返回状态处理*/
function tipData(data) {
    var message = data.message;
    if (data.status == 0) {
        /*操作成功*/
        if (message) {
            layer.msg(data.message, {icon: 1, time: 2000});
        }
        return true;
    } else if (data.status == -3) {
        /*没有登录或Session过期*/
        window.location = basePath + 'direct/login.htm';
        return false;
    } else if (data.status == -2 || data.status == -1) {
        /*-2：权限不足; -1：系统异常*/
        if (message) {
            layer.msg(data.message, {icon: 5, time: 2000});
        }
        return false;
    } else if (data.status == 1) {
        /*重复提交*/
        return false;
    } else if (data.status == 2) {
        /*操作失败*/
        if (message) {
            layer.msg(data.message, {icon: 2, time: 2000});
        }
        return true;
    } else if (data.status == 3) {
        /*后台验证参数失败*/
        if (message) {
            layer.msg(data.message, {icon: 5, time: 2000});
        }
        return true;
    }
};

/*ajax请求返回JSON结果*/
function ajaxSubmitResponseJSON(obj) {
    var defaults = {
        url: '',
        method: 'GET',
        data: '',
        success: $.noop
    }
    var options = $.extend(defaults, obj);
    if (options.url) {
        var data = 'act=ajax';
        if (options.data) {
            data += ('&' + options.data);
        }
        $.ajax({
            type: options.method,
            url: basePath + options.url,
            data: data,
            dataType: 'json',
            async: true,
            success: function (data) {
                if (tipData(data)) {
                    options.success(data);
                }
            }
        });
    }
};

/*ajax请求返回内容为html替换dialog弹出层内容*/
function ajaxDialogResponseHtm(obj) {
    var defaults = {
        container: _dialog_window,
        url: '',
        method: 'GET',
        data: '',
        success: $.noop
    };
    var options = $.extend(defaults, obj);
    if (options.url) {
        var data = 'act=ajax';
        if (options.data) {
            data += ('&' + options.data);
        }
        $.ajax({
            type: options.method,
            url: basePath + options.url,
            data: data,
            async: false,
            dataType: 'html',
            success: function (data) {
                var container = options.container;
                if (container && typeof container === 'object') {
                    container.content(data);
                }
            }
        });
    }
};

/*ajax请求返回内容为html*/
function ajaxSubmitResponseHtm(obj) {
    var defaults = {
        container: '#data-wrapper',
        url: '',
        method: 'GET',
        data: '',
        success: $.noop
    }
    var options = $.extend(defaults, obj);
    if (options.url) {
        var data = 'act=ajax';
        if (options.data) {
            data += ('&' + options.data);
        }
        $.ajax({
            type: options.method,
            url: basePath + options.url,
            data: data,
            async: false,
            dataType: 'html',
            success: function (data) {
                try {
                    /*如果返回的data为json数据，data.status有如下值： -3：未登录；-2：权限不足；-1：系统异常*/
                    tipData(eval('(' + data + ')'));
                } catch (e) {
                    /*返回的data为html数据*/
                    var container = options.container;
                    if (!container || '' == $.trim(container)) {
                        container = '#data-wrapper';
                    }
                    if ('#data-wrapper' == container) {
                        $(container).html(data);
                    } else if ('#pop-wrapper' == container) {
                        $(container).append(data);
                    }
                }
            }
        });
    }
};

/*multipart 提交表单*/
function ajaxMultiSubmitResponseJSON(obj) {
    var defaults = {
        url: '',
        form: '',
        method: 'POST',
        success: $.noop
    }
    var ext = $.extend(defaults, obj);
    if (ext.form && ext.url) {
        $(ext.form).ajaxSubmit({
            url: ext.url,
            method: ext.method,
            success: function (data) {
                if (tipData(data)) {
                    ext.success(data);
                }
            }
        });
    }
};

/*获取url中的参数*/
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);
    //匹配目标参数
    if (r)
        return decodeURI(r[2]);
    return '';
    //返回参数值
};

//获取随机数，number多少位
var getRandom = function (number) {
    var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
    var ret = "";
    var regex = /^\+?[1-9]*$/;
    if (!regex.test(number)) {
        number = 3;
    }
    for (var i = 0; i < number; i++) {
        var id = Math.ceil(Math.random() * 35);
        ret += chars[id];
    }
    return ret;
};

/*调用方法关闭弹窗-layer 表示第几层弹窗*/
function closeLayer(layer) {
    if (layer != undefined && layer >= 0) {
        $('#pop-wrapper > div:eq(' + layer + ')').remove();
        return;
    }
    $('#pop-wrapper > div:last').remove();
};

function UiConfirm(obj) {
    var defaults = {
        title: '提示',
        message: '',
        success: $.noop
    }
    var ext = $.extend(defaults, obj);
    var htm = '<div class="pop-background"><div class="col-md-5"><div class="popup popup5 popup-small"><div class="panel-heading">';
    htm += '<div class="panel-btns"><a class="panel-close btn-4-hide">x</a></div><h3 class="panel-title">' + ext.title + '</h3>';
    htm += '</div><div class="panel-add-to"><div class="row"><div class="panel-body panel-body-ws"><div class="col-md-6">';
    htm += '<div class="form-group text-c font14"><span class=" color-red">' + ext.message + '</span></div></div></div></div>';
    htm += '<div class="btn-group2-s"><div class="panel-body panel-body2"><div class="btn-group2 left ">';
    htm += '<button class="btn btn-primary btn-4-confirm">确定</button>';
    htm += '<button class="btn btn-default btn-4-hide">取消</button></div></div></div></div></div></div></div>';
    $('#pop-wrapper').append(htm);
    $('#pop-wrapper .btn-4-confirm').off('click').on('click', function () {
        closeLayer();
        ext.success();
    });
    $('.popup-small,.panel-alt').dragging({  //--弹窗拖动
        move: 'both',
        randomPosition: false,
        hander: '.panel-heading'
    });
};

function Layer(options) {
    var defaults = {
        message: "",
        X: 'center', //--默认水平居中
        Y: 'center', //--默认垂直居中,设置不居中以数字表示
        time: 1000,
        callback: $.noop
    };
    var ext = $.extend(defaults, options);
    /*var wh = $(window).height();
     var divh = $(".jshtbox").height();
     var tp = (wh - divh) / 2;*/
    var htm = '<div class="status-tips" id="mydailbox"><div class="col-ms-9">';
    htm += '<div class=" panel text-c font13" style="margin-top:150px; border-top:1px solid #ccc; border-left:1px solid #ccc;">';
    htm += '<span class="color-green">' + ext.message + '</span></div></div></div>';
    $("body").append(htm);
    $("#mydailbox").delay(ext.time).animate({opacity: '0'}, 500, function () {
        $(this).remove();
        if (ext.callback) {
            ext.callback();
        }
    })
};

//**---价格加千分位
function numFormat(input) {
    var n = parseFloat(input).toFixed(2);
    var re = /(\d{1,3})(?=(\d{3})+(?:\.))/g;
    return n.replace(re, "$1,");
};
//--数字千分位
function numFormat2 (num) {
    return (num + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
};

/**
 *只能输入整数
 */
var inputInt = function(e) {
    var eve = e;
    var s = eve.keyCode;
    var sh = eve.shiftKey;
    var ctl = eve.ctrlKey;
    if (ctl || (!sh && s != 32 && ((s >= 19 && s <= 57) || (s >= 96 && s <= 105) || (s == 8 || s == 9)))) {
        //eve.returnValue = true;
        return true;
    } else {
        //eve.returnValue = false;
        return false;
    }
};
/**
 * 只能输入浮点数
 * 对onkeydown事件有效
 */
var inputFloat = function(s) {
    var e = event.keyCode;
    var sh = window.event.shiftKey;
    if (e == 8 || e == 9) {
        window.event.returnValue = true;
    } else if (!sh && e >= 19 && e <= 57 || e >= 96 && e <= 105) {
        if (s.indexOf(".") < s.length - 2 && s.indexOf(".") > 0) {
            window.event.returnValue = false;
        } else {
            window.event.returnValue = true;
        }
    } else if (e == 110 || e == 190) {
        if (s.indexOf(".") < 0 && s != "") {
            window.event.returnValue = true;
        } else {
            window.event.returnValue = false;
        }
    } else {
        window.event.returnValue = false;
    }
};
//阻止事件冒泡的通用函数
var stopBubble = function(e) {
    // 如果传入了事件对象，那么就是非ie浏览器
    if (e && e.stopPropagation) {
        //因此它支持W3C的stopPropagation()方法
        e.stopPropagation();
    } else {
        //否则我们使用ie的方法来取消事件冒泡
        window.event.cancelBubble = true;
    }
};
//临时转换器
var record = {
    num : ""
};
//验证输入
var checkInput = function(reg, n) {
    var val = n.val();
    if (val != "" && reg.test(val)) {
        record.num = val;
    } else {
        if (val != "") {
            n.val(record.num);
        }
    }
};
//关键词验证
var chkKeyWord = function(n) {
    var keyWordreg = /^[\u4E00-\u9FA5\uf900-\ufa2d\w\d\s]+$/;
    checkInput(keyWordreg, n);
};
//价格验证
var checkDecimal = function(n) {
    var priceReg = /^\d{0,10}\.{0,1}(\d{1,2})?$/;
    checkInput(priceReg, n);
};
var checkInteger = function(n) {
    var reg = /^\+?[1-9][0-9]*$/;
    checkInput(reg, n);
};
//正整数
var isNum = function(n) {
    var reg = /^\+?[1-9][0-9]*$/;
    return reg.test(n);
};
//校验手机号码：必须以数字开头，除数字外，可含有“-”
function isMobil(s)
{
    var patrn=/^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/;
    if (!patrn.exec(s)) return false
    return true
}
//校验是否全由数字组成
function isDigit(s)
{
    var patrn=/^[0-9]{1,20}$/;
    if (!patrn.exec(s)) return false
    return true
}

//spu填写验证
var spu_test= function (spu) {
    var _first = spu.substr(0,1);
    if (_first == "F"){
        var _s1 = spu.split("*");
        if (_s1.length >= 2) {
            var _s2 = _s1[0].length;
            if (_s2 == 2) {
                tipData({message:"驱动方式不能为空",status:-1});
                return false;
            }
            if (_s2 == 3) {
                tipData({message:"连接方式不能为空",status:-1});
                return false;
            }
            if (_s2 == 5) {
                tipData({message:"结构形式不能为空",status:-1});
                return false;
            }
            if (_s2 == 6) {
                tipData({message:"压力等级不能为空",status:-1});
                return false;
            }
            if (_s2 == 7) {
                tipData({message:"阀体材料不能为空",status:-1});
                return false;
            }
            if (_s2 == 9) {
                tipData({message:"密封面材料不能为空",status:-1});
                return false;
            }
            if (_s2 == 11) {
                tipData({message:"内部件材料不能为空",status:-1});
                return false;
            }
            if (_s2 == 12) {
                tipData({message:"设计标准不能为空",status:-1});
                return false;
            }
            return true;
        }else {
            return true;
        }
    }
}